package com.jd.user.service.impl;

import com.jd.basic.config.BusinessException;
import com.jd.basic.constant.VerifyCodeConstants;
import com.jd.basic.service.impl.BaseServiceImpl;
import com.jd.basic.util.MD5Utils;
import com.jd.basic.util.StrUtils;
import com.jd.user.domain.Logininfo;
import com.jd.user.domain.User;
import com.jd.user.dto.UserDto;
import com.jd.user.mapper.LogininfoMapper;
import com.jd.user.mapper.UserMapper;
import com.jd.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JavaMailSender javaMailSender;



    @Override
    public void remove(Long id) {
        User user = userMapper.loadById(id);
        //删除登录信息表数据
        logininfoMapper.remove(user.getLogininfoId());
        //删除用户信息
        super.remove(id);
    }

    @Override
    public void update(User user) {
        //1.处理密码和盐值
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Password = MD5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Password);
        //用户user:createtime和logininfo_id不能修改

        //获取登录信息id
        Long logininfoId = user.getLogininfoId();
        //登录信息logininfo:type不修改
        Logininfo logininfo = user2Logininfo(user);
        logininfo.setId(logininfoId);
        logininfoMapper.update(logininfo);
        super.update(user);
    }

    @Override
    public void patchDelete(Long[] ids) {
        //批量删除登录信息对象
        for (Long id : ids) {
            User user = userMapper.loadById(id);
            logininfoMapper.remove(user.getLogininfoId());
        }
        //批量删除用户信息
        super.patchDelete(ids);
    }

    private User userDto2User(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密后的密码
        String md5Password = MD5Utils.encrypByMd5(userDto.getPassword()+salt);
        user.setSalt(salt);
        user.setPassword(md5Password);
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //按照同名属性赋值【username，email，phone，salt，password】
        BeanUtils.copyProperties(user, logininfo);
        //由于当前对象为用户,需要设置Type = 1;
        logininfo.setType(1);
        return logininfo;
    }

    /**
     * 手机号注册
     * @param userDto
     */
    @Override
    public void phoneRegister(UserDto userDto) {
        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();
        //1. 校验
        //1.1 校验空值
        if (StringUtils.isEmpty(phone)) {
            throw new BusinessException("请输入phone");
        }
        if (StringUtils.isEmpty(phoneCode)) {
            throw new BusinessException("请输入phoneCode");
        }
        if (StringUtils.isEmpty(password)) {
            throw new BusinessException("请输入password");
        }
        if (StringUtils.isEmpty(passwordRepeat)) {
            throw new BusinessException("请输入passwordRepeat");
        }
        //1.2判断两次密码是否相同
        if (!password.equals(passwordRepeat)) {
            throw new BusinessException("两次密码不一致");
        }
        //1.3验证码是否过期
        Object redisSmsCode = redisTemplate.opsForValue().get(VerifyCodeConstants.REGISTER_CODE_PREFIX + phone);
        if (redisSmsCode == null) {
            throw new BusinessException("手机验证码过期");
        }
        //1.4验证码是否正确
        String codeTmp = redisSmsCode.toString().split(":")[0];
        if (!codeTmp.equalsIgnoreCase(phoneCode)) {
            throw new BusinessException("手机验证码错误");

        }
        //2.保存数据
        //2.1 先保存t_logininfo
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);

        logininfoMapper.save(logininfo); //自增
        //2.2 再保存t_user

        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);

    }

    /**
     * 邮箱注册
     * @param userDto
     * @throws MessagingException
     */
    @Override
    public void emailRegister(UserDto userDto) throws MessagingException {
        String email = userDto.getEmail();
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();
        String imageCode = userDto.getImageCode();
        String imageCodeKey = userDto.getImageCodeKey();
        //1. 校验
        //1.1 校验空值
        if (StringUtils.isEmpty(email)) {
            throw new BusinessException("请输入email");
        }
        if (StringUtils.isEmpty(password)) {
            throw new BusinessException("请输入password");
        }
        if (StringUtils.isEmpty(passwordRepeat)) {
            throw new BusinessException("请输入passwordRepeat");
        }
        if (StringUtils.isEmpty(imageCodeKey)){
            throw new BusinessException("请刷新页面重新获取图形验证码");
        }
        if (StringUtils.isEmpty(imageCode)){
            throw new BusinessException("验证码不能为空");
        }
        //1.2判断两次密码是否相同
        if (!password.equals(passwordRepeat)) {
            throw new BusinessException("两次密码不一致");
        }
        //2.校验 — 图形验证码校验
        //2.1 校验图形验证码是否过期
        //使用get方法通过key值获取验证码的值Value
        Object imageCodeValue = redisTemplate.opsForValue().get(imageCodeKey);
        if (imageCodeValue == null){
            throw new BusinessException("图形验证码过期,请重新获取");
        }
        //3. 校验图形验证码是否正确
        if (!imageCodeValue.toString().equalsIgnoreCase(imageCode)){
            throw new BusinessException("验证码错误,请重新输入");
        }
        //4.校验邮箱是否注册
        User user = userMapper.loadByEmail(email);
        if (user != null){
            throw new BusinessException("该邮箱已注册,请直接登录");
        }
        //2.保存数据
        //2.1 先保存t_logininfo

        User user1 = userDto2UserB(userDto);

        Logininfo logininfo1 = user2LogininfoB(user1);

        logininfoMapper.save(logininfo1); //自增
        //2.2 再保存t_user

        user1.setLogininfoId(logininfo1.getId());
        userMapper.save(user1);
        //3.发送邮件：审核通过邮件 - 叫他激活
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
        //设置发送方
        helper.setFrom("461561986@qq.com");
        //设置主题
        helper.setSubject("店铺激活邮件");
        //设置内容
        helper.setText("<h1>点击激活账号!!!</h1>" +
                "<a href='http://localhost:8080/user/active/"+user1.getId()+"'>点击该链接激活</a>",true);
        //添加附件
        helper.addAttachment("IMG_5140.JPG",new File("D:\\resources\\IMG_5140.JPG"));
        //收件人
        helper.setTo("2335318805@qq.com");
        javaMailSender.send(mimeMessage);

    }

    private User userDto2UserB(UserDto userDto) {
        User user1 = new User();
        user1.setUsername(userDto.getEmail());
        user1.setEmail(userDto.getEmail());
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密后的密码
        String md5Password = MD5Utils.encrypByMd5(userDto.getPassword()+salt);
        user1.setSalt(salt);
        user1.setPassword(md5Password);
        //设置状态 - 未激活
        user1.setState(0);
        return user1;
    }

    private Logininfo user2LogininfoB(User user1) {
        Logininfo logininfo1 = new Logininfo();
        //按照同名属性赋值【username，email，phone，salt，password】
        BeanUtils.copyProperties(user1, logininfo1);
        //由于当前对象为用户,需要设置Type = 1;
        logininfo1.setType(1);
        return logininfo1;
    }
}
